package TukuduDemo;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

import org.apache.log4j.Logger;




public class ConnectionFactory {
	
	private static Logger log = Logger.getLogger(ConnectionFactory.class);
	private	static ConnectionFactory instance = new ConnectionFactory();
	private Properties prop= new Properties();
	
	private static String url;
	private static String username;
	private static String password;
	private static String driver;
	private static Connection connection;
	
	public static Connection getConnection(){
		return instance.createConnection();
	}
	
	private Connection createConnection(){
		
		try{
			connection = DriverManager.getConnection(url, username, password);
		}catch(SQLException se){
			
			log.error("Unable to connect to database");
			log.error(se);
		}	
		return connection;
	}
	
	private ConnectionFactory(){
		initialize();
	}
	
	private void initialize(){
		
		try{
			prop.load(new FileInputStream("application.properties"));
			url = prop.getProperty("url");
			username = prop.getProperty("username");
			password = prop.getProperty("password");
			driver = prop.getProperty("driver");
			System.out.println(driver);
			Class.forName(driver);
			log.info("Using Driver : "+driver);
			log.info("Driver registration Successful");			
		}catch(FileNotFoundException e){
			System.out.println("File not found");
			log.error("application.properties no found");
			log.error(e);
		}catch(IOException ioe){
			log.error("Error occured while reading application properties. Please check if the file has read access or not");
			log.error(ioe);
		}catch(ClassNotFoundException cnfe){
			log.error("Driver Initialization Failed");
			log.error(cnfe);
		}
	}
}
